//
//  HMNetworkTools.swift
//  05-Swift网络工具类
//
//  Created by itteacher on 2017/7/23.
//  Copyright © 2017年 itteacher. All rights reserved.
//

import UIKit
import AFNetworking


//  网络请求类型
enum RequestType {
    //  get请求
    case get
    //  post请求
    case post
}

//  网络请求工具类
class HMNetworkTools: AFHTTPSessionManager {
    
    //  单例的全局访问点
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        //  添加可接收的服务端数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    //  private: 只能在当前类中使用
    //  fileprivate: 文件私有的意思，可以在当前文件中使用
    //  封装GET和POST请求
    fileprivate func request(type: RequestType, urlStr: String, params: Any?,  finishCallBack: @escaping (Any?, Error?)->()) {
        if type == .get {
            self.get(urlStr, parameters: params, progress: nil, success:
                { (_, response: Any?) in
                finishCallBack(response, nil)
            }, failure: { (_, error: Error) in
                finishCallBack(nil, error)
            })
        } else {
            self.post(urlStr, parameters: params, progress: nil, success: { (_, response) in
                finishCallBack(response, nil)
            }, failure: { (_, error) in
                finishCallBack(nil, error)
            })
        }
    }

}

//  MARK: --   首页相关接口
extension HMNetworkTools {
    
    /// 发送带有图片的微博
    ///
    /// - Parameters:
    ///   - access_token: 令牌
    ///   - status: 微博内容
    ///   - pic: 图片
    ///   - callBack: 闭包回调
    func sendWeibo(access_token: String, status: String, pic: UIImage, callBack: @escaping (Any?, Error?) -> ()) {
        //  接口地址
        let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
        //  接口参数
        let params = [
            "access_token": access_token,
            "status": status
        ]
        //  把图片转成二进制  compressionQuality: 图片质量系数，系数越大图片越清晰
        let imageData = UIImageJPEGRepresentation(pic, 0.5)!
//        //  写入到桌面
//        try! imageData.write(to: URL(fileURLWithPath: "/Users/itteacher/Desktop/1.jpg"))
//        //  把图片转成png的二进制
//        let imageData1 = UIImagePNGRepresentation(pic)!
//        //  写入到桌面
//        try! imageData1.write(to: URL(fileURLWithPath: "/Users/itteacher/Desktop/2.png"))
        
        post(urlStr, parameters: params, constructingBodyWith: { (formData) in
            //  withFileData: 图片二进制
            //  name: 服务端定义上传图片的参数
            //  fileName： 文件名
            //  mimeType: 资源类型
            formData.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
        }, progress: nil, success: { (_, response) in
            callBack(response,nil)
        }) { (_, error) in
            callBack(nil,error)
        }
    }
    
    ///  发送文字微博
    ///
    /// - Parameters:
    ///   - access_token: 令牌
    ///   - status: 文字内容
    ///   - callBack: 闭包回调
    func sendWeibo(access_token: String, status: String, callBack: @escaping (Any?, Error?) -> ()) {
        //  接口地址
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        //  接口参数
        let params = [
            "access_token": access_token,
            "status": status
        ]
        //  发送网络请求
        request(type: .post, urlStr: urlStr, params: params, finishCallBack: callBack)
    }
    
    /// 获取登录及其所关注的微博用户数据
    ///
    /// - Parameters:
    ///   - access_token: 令牌
    ///   - callBack: 闭包回调
    func requestStatuses(access_token: String, maxId: Int64 = 0, sinceId: Int64 = 0, callBack: @escaping (Any?, Error?) -> ()) {
        //  接口地址
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        //  接口参数
        let params: [String: Any] = [
            "access_token": access_token,
            "max_id": maxId,
            "since_id": sinceId
        ]
        print(urlStr + "?access_token=\(access_token)")
        //  加载网络数据
        request(type: .get, urlStr: urlStr, params: params, finishCallBack: callBack)
    }
}


//  MARK: --   OAuth授权相关接口
extension HMNetworkTools {
    
    /// 获取用户信息
    ///
    /// - Parameters:
    ///   - access_token: 令牌
    ///   - uid: 用户id
    ///   - callBack: 闭包回调
    func requestUserInfo(access_token: String, uid: Int64, callBack: @escaping (Any?, Error?) -> ()) {
        //  接口地址
        let urlStr = "https://api.weibo.com/2/users/show.json"
        //  接口参数
        let params: [String: Any] = [
            "access_token": access_token,
            "uid": uid
        ]
        
        print(urlStr + "?access_token=\(access_token)&uid=\(uid)")
        
        //  加载网络请求
        request(type: .get, urlStr: urlStr, params: params, finishCallBack: callBack)
    }

    /// 获取令牌
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - callBack: 闭包回调
    func requestAccessToken(code: String, callBack: @escaping (Any?, Error?) -> ()) {
        //  接口地址
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        //  接口参数
        let params = [
            "client_id": AppKey,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": Redirect_uri
        ]
        //  加载网络请求
        request(type: .post, urlStr: urlStr, params: params, finishCallBack: callBack)
    }
    
    
}





